package com.chengwei.ch.busdemo.utils;

import android.graphics.Color;

public class CleanColorHelper {

    /** 颜色列表，依次是红橙绿 */
    private static final int[] COLORS = {
            // 红
            0xffff5252, //
            0xfffe6530, //
            0xffff8d22, //
            0xffffb619, //
            // 黄
            0xfffcd038, //
            0xffb5eb12, //
            0xff7ad845, //
            // 绿
            0xff54d36f,
            //蓝
            0xff32a7de

    };

    /**
     * 调用者控制变色的节奏
     *
     * @param percent 百分数
     */
    public static int manualUpdateColor(Colors startColor, Colors endColor, int percent) {
        if (percent > 100) {
            percent = 100;
        } else if (percent < 0) {
            percent = 0;
        }
        // 8->0 30%
        final int startColorIdx = getColorIdx(startColor);
        final int endColorIdx = getColorIdx(endColor);
        final float newPosition = startColorIdx + (float) (endColorIdx - startColorIdx) * percent / 100;

        int showColor ;
        if (newPosition == startColorIdx || newPosition == endColorIdx) {
            showColor = COLORS[(int) newPosition];
        } else {
            int currentIdx ;
            int nextIdx ;
            float offset ;
            if (endColorIdx < startColorIdx) {
                currentIdx = (int) newPosition + 1;
                nextIdx = currentIdx - 1;
                offset = currentIdx - newPosition;
            } else {
                currentIdx = (int) newPosition;
                nextIdx = currentIdx + 1;
                offset = newPosition - currentIdx;
            }
            final int currentColor = COLORS[currentIdx];
            final int nextColor = COLORS[nextIdx];
            showColor = getShowColor(currentColor, nextColor, offset);
        }
        return showColor;
    }

    private static int getShowColor(int colorStart, int colorEnd, float offset) {
        final int startRed = Color.red(colorStart);
        final int startGreen = Color.green(colorStart);
        final int startBlue = Color.blue(colorStart);
        final int endRed = Color.red(colorEnd);
        final int endGreen = Color.green(colorEnd);
        final int endBlue = Color.blue(colorEnd);
        final int showRed = (int) (startRed + offset * (endRed - startRed));
        final int showGreen = (int) (startGreen + offset * (endGreen - startGreen));
        final int showBlue = (int) (startBlue + offset * (endBlue - startBlue));
        return Color.argb(255, showRed, showGreen, showBlue);
    }

    private static int getColorIdx(Colors color) {
        switch (color) {
            case RED:
                return 0;
            case ORANGE:
                return 4;
            case GREEN:
                return 8;
        }
        return 8;
    }

    public static enum Colors {
        RED, ORANGE, GREEN
    }
}
